/**
 * 
 */
package com.zhisheng.core.security.support;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.dao.DataAccessException;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.zhisheng.core.security.dao.SystemDao;
import com.zhisheng.core.security.entity.Resource;
import com.zhisheng.core.security.entity.User;



/**
 * @author qzhou
 */
@Service("securityManager")
public class SecurityManagerSupport implements UserDetailsService{

 
    
	@javax.annotation.Resource
    private SystemDao systemDao;
    
    /* (non-Javadoc)
     * @see org.springframework.security.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
     */
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, DataAccessException {
        List<User> users = systemDao.getUserByName(userName);
        if(users.isEmpty()) {
            throw new UsernameNotFoundException("User " + userName + " has no GrantedAuthority");
        }
        return users.get(0);
    }
    
    
    /* (non-Javadoc)
     * @see com.demo2do.vader.security.SecurityManager#listUrlAuthorities()
     */
    public Map<String, String> listUrlAuthorities() {
        Map<String, String> urlAuthorities = new HashMap<String, String>();
        List<Resource> urlResources = systemDao.listUrlResources("URL");
        for(Resource resource : urlResources) {
            urlAuthorities.put(resource.getValue(), resource.getRoleAuthorities());
        }
        return urlAuthorities;
    }

    
}
